"""
配置模块
处理应用配置
"""

import os
import json
import logging
from typing import Dict, Any

logger = logging.getLogger(__name__)

# 默认配置
CONFIG = {
    # API配置
    "api_url": "https://api.example.com/v1",
    "timeout": 30,  # 秒
    "max_retries": 3,
    "retry_delay": 2,  # 秒
    
    # 缓存配置
    "cache_dir": os.path.join(os.path.expanduser("~"), ".cache", "sample_project"),
    "cache_max_age": 3600,  # 秒
    
    # 输出配置
    "output_dir": "output",
    "default_format": "json",
    
    # 日志配置
    "log_level": "INFO",
    "log_file": None,  # 如果为None，则只输出到控制台
    
    # 其他配置
    "default_group_by": "type",
    "default_sort_by": "created_at",
    "default_sort_order": "desc"
}

def load_config(config_path: str) -> Dict[str, Any]:
    """
    从文件加载配置
    
    Args:
        config_path: 配置文件路径
        
    Returns:
        配置字典
    """
    if not os.path.exists(config_path):
        logger.warning(f"配置文件不存在: {config_path}")
        return {}
    
    try:
        with open(config_path, 'r') as f:
            user_config = json.load(f)
        
        logger.info(f"从 {config_path} 加载了配置")
        return user_config
    
    except json.JSONDecodeError:
        logger.error(f"配置文件格式错误: {config_path}")
        return {}
    
    except Exception as e:
        logger.error(f"加载配置文件失败: {e}")
        return {}

def save_config(config: Dict[str, Any], config_path: str) -> bool:
    """
    保存配置到文件
    
    Args:
        config: 配置字典
        config_path: 配置文件路径
        
    Returns:
        是否成功
    """
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        
        with open(config_path, 'w') as f:
            json.dump(config, f, indent=2)
        
        logger.info(f"配置已保存到 {config_path}")
        return True
    
    except Exception as e:
        logger.error(f"保存配置失败: {e}")
        return False

def ensure_dir(directory: str) -> bool:
    """
    确保目录存在，如果不存在则创建
    
    Args:
        directory: 目录路径
        
    Returns:
        是否成功
    """
    if not directory:
        return False
    
    try:
        os.makedirs(directory, exist_ok=True)
        return True
    except Exception as e:
        logger.error(f"创建目录失败: {e}")
        return False

def get_config_path() -> str:
    """
    获取默认配置文件路径
    
    Returns:
        配置文件路径
    """
    config_dir = os.path.join(os.path.expanduser("~"), ".config", "sample_project")
    ensure_dir(config_dir)
    return os.path.join(config_dir, "config.json")